<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>JavaScript【闭包】closure</title>
    <script src="../js/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        /*
         * 闭包（closure）
         * 设计到变量的作用域
         * 变量分类： 全局变量和局部变量
         * JavaScript的特殊之处：局部函数内部可以直接读取全局变量
         */
        function f1() {
            var n = 999;

            function f2() {
                alert(n);
            }

            return f2;
        }

        var result = f1();
        result();

        //代码片段1
        var eg1_name = "The Window";
        var eg1_closure_fn = {
            eg1_name: "My Object",
            getNameFunc: function () {
                return function () {
                    return this.eg1_name;
                };
            }
        };
        console.log(eg1_closure_fn.getNameFunc()());

        //代码片段2
        var eg2_name = "The Window";
        var eg2_closure_fn = {
            eg2_name: "My Object",
            getNameFunc: function () {
                var that = this;
                return function () {
                    return that.eg2_name;
                };
            }
        };
        console.log(eg2_closure_fn.getNameFunc()());


        /*
         *应用
         * 如何点击每一列的时候 alert 其 index ?
         */
        window.onload = function () {
            var ul = document.getElementById("test");
            var lis = ul.getElementsByTagName('li');
            for (var i = 0; i < lis.length; i++) {
                lis[i].onclick = (function (num) {
                    return function () {
                        alert(num);
                    }
                })(i);
            }
        }
    </script>
</head>
<body>
<ul id="test">
    <li>这是第一条</li>
    <li>这是第二条</li>
    <li>这是第三条</li>
</ul>
</body>
</html>